//
//  CouponViewController.m
//  TerritoryShopkeeper
//
//  Created by 李小龙 on 2017/12/4.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "CouponViewController.h"
#import "TitleSelectionView.h"
#import "CouponTableViewCell.h"

@interface CouponViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (nonatomic, strong) TitleSelectionView *titleView;
@property (nonatomic, strong) NSMutableArray *titleCountArray;//1未使用 2已使用 3可领取

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewTLayout;
@property (nonatomic, strong) NSMutableArray<CouponModel *> *usableArray;
@property (nonatomic, assign) NSInteger usablePage;
@property (nonatomic, strong) NSMutableArray<CouponModel *> *unusedArray;
@property (nonatomic, assign) NSInteger unusedPage;
@property (nonatomic, strong) NSMutableArray<CouponModel *> *usedArray;
@property (nonatomic, assign) NSInteger usedPage;

@end

@implementation CouponViewController
#pragma mark - Get
- (NSMutableArray *)titleCountArray {
    if (!_titleCountArray) {
        _titleCountArray = [[NSMutableArray alloc] init];
    }
    return _titleCountArray;
}
- (TitleSelectionView *)titleView {
    if (!_titleView) {
        _titleView = [[TitleSelectionView alloc] initWithBackColor:[UIColor whiteColor] TextColor:[UIColor gray66Color] SelectTextColor:[UIColor ThemeColor]];
        [_titleView setFrame:CGRectMake(0, 0, ScreenWidth, 44)];
        [_titleView setTitleWithArrs:@[@"可领取",@"未使用",@"使用记录"]  withShowIndex:0 lineWidth:ScreenWidth/3.0-46];
    }
    return _titleView;
}
- (NSMutableArray<CouponModel *> *)usableArray {
    if (!_usableArray) {
        _usableArray = [[NSMutableArray alloc] init];
    }
    return _usableArray;
}
- (NSMutableArray<CouponModel *> *)unusedArray {
    if (!_unusedArray) {
        _unusedArray = [[NSMutableArray alloc] init];
    }
    return _unusedArray;
}
- (NSMutableArray<CouponModel *> *)usedArray {
    if (!_usedArray) {
        _usedArray = [[NSMutableArray alloc] init];
    }
    return _usedArray;
}
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"优惠券";
    [self hiddenShadowImage:NO];
    
    self.usablePage = 1;
    self.unusedPage = 1;
    self.usedPage = 1;
    
    [self createUI];
    
    [self getNetCouponCount];
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self getNetData];
}
#pragma mark - action
- (void)rightButtonAction:(id)sender {
    if (self.block) {
        self.block(nil);
    }
    [super disMissSelf];
}
- (void)createUI {
    __block typeof(self) blockSelf = self;
    
    [self.view addSubview:self.titleView];
    switch (self.type) {
        case CouponFromTypeMine:
        {
            [self.titleView setHidden:NO];
            self.tableViewTLayout.constant = 44;
        } break;
        case CouponFromTypeGoodsDetail:
        {
            [self.titleView setHidden:YES];
            self.tableViewTLayout.constant = 0;
        } break;
        case CouponFromTypeShopcartOrder: case CouponFromTypeGoodsOrder:
        {
            [self.titleView setHidden:YES];
            self.tableViewTLayout.constant = 0;
            self.titleView.currentIndex = 1;
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"不使用" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction:)];
        } break;
        default:
            break;
    }
    
    self.titleView.block = ^(NSInteger index) {
        NSMutableArray *array;
        switch (index) {
            case 0:
                array = blockSelf.usableArray;
                break;
            case 1:
                array = blockSelf.unusedArray;
                break;
            case 2:
                array = blockSelf.usedArray;
                break;
            default:
                break;
        }
        if (array.count == 0) {
            [MBProgressHUD showHUDProgress:blockSelf.view animated:YES];
            [blockSelf getNetData];
        } else {
            [blockSelf.tableView reloadData];
        }
    };
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        switch (blockSelf.titleView.currentIndex) {
            case 0:
            {
                _usablePage = 1;
            } break;
            case 1:
            {
                _unusedPage = 1;
            } break;
            case 2:
            {
                _usedPage = 1;
            } break;
            default:
                break;
        }
        [blockSelf getNetData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        switch (blockSelf.titleView.currentIndex) {
            case 0:
            {
                _usablePage++;
            } break;
            case 1:
            {
                _unusedPage++;
            } break;
            case 2:
            {
                _usedPage++;
            } break;
            default:
                break;
        }
        [blockSelf getNetData];
    }];
    
    [self.tableView.mj_footer setHidden:YES];
}
- (void)updateTitleView {
    NSString *usableStr, *unusedStr, *usedStr;
    if ([[self.titleCountArray objectAtIndex:2] integerValue] > 0) {
        usableStr = [NSString stringWithFormat:@"可领取(%@)",[self.titleCountArray objectAtIndex:2]];
    } else {
        usableStr = @"可领取";
    }
    if ([[self.titleCountArray objectAtIndex:0] integerValue] > 0) {
        unusedStr = [NSString stringWithFormat:@"未使用(%@)",[self.titleCountArray objectAtIndex:0]];
    } else {
        unusedStr = @"未使用";
    }
    if ([[self.titleCountArray objectAtIndex:1] integerValue] > 0) {
        usedStr = [NSString stringWithFormat:@"已使用(%@)",[self.titleCountArray objectAtIndex:1]];
    } else {
        usedStr = @"已使用";
    }
    [self.titleView setTitleWithArrs:@[usableStr,unusedStr,usedStr] withShowIndex:self.titleView.currentIndex lineWidth:ScreenWidth/3.0-46];
}
- (void)exchangeAction:(CouponModel *)model {
    [self showAlertWithTitleArray:@[@"取消",@"确认"] title:@"温馨提示" message:[NSString stringWithFormat:@"兑换该优惠券需要消耗%@积分\n确认兑换？",model.mcintegral] alertStyle:UIAlertControllerStyleAlert];
    __block typeof(self) blockSelf = self;
    self.alertBlock = ^(NSString *actionTitle) {
        if ([actionTitle isEqualToString:@"确认"]) {
            [blockSelf exchangeNetWork:model];
        }
    };
}
#pragma mark - 网络请求
- (void)exchangeNetWork:(CouponModel *)model {
    //MARK: 兑换优惠券
    __block typeof(self) blockSelf = self;
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Save_MyCoupon parameters:@{@"cid":model.cid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            blockSelf.usablePage = 1;
            blockSelf.unusedPage = 1;
            blockSelf.usedPage = 1;
            [MBProgressHUD showHUDProgress:blockSelf.view animated:YES];
            [blockSelf getNetData];
            [blockSelf getNetCouponCount];
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)endRefresh {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}
- (void)getNetFailure {
    switch (self.titleView.currentIndex) {
        case 0:
        {
            if (_usablePage != 1) {
                _usablePage--;
            }
        } break;
        case 1:
        {
            if (_unusedPage != 1) {
                _unusedPage--;
            }
        } break;
        case 2:
        {
            if (_usedPage != 1) {
                _usedPage--;
            }
        } break;
        default:
            break;
    }
}
- (void)getNetSuccess:(NSDictionary *)dics {
    [self.tableView.mj_footer setHidden:YES];
    
    NSMutableArray *tableArray;
    NSInteger page = 0;
    switch (self.titleView.currentIndex) {
        case 0:
        {
            tableArray = self.usableArray;
            page = self.usablePage;
        } break;
        case 1:
        {
            tableArray = self.unusedArray;
            page = self.unusedPage;
        } break;
        case 2:
        {
            tableArray = self.usedArray;
            page = self.usedPage;
        } break;
        default:
            break;
    }
    if ([dics isKindOfClass:[NSArray class]]) {
        [tableArray removeAllObjects];
        for (NSDictionary *dic in dics) {
            CouponModel *model = [CouponModel mj_objectWithKeyValues:dic];
            [tableArray addObject:model];
        }
        [self.tableView reloadData];
        return;
    }
    if ([dics[@"totalRow"] integerValue] > tableArray.count) {
        [self.tableView.mj_footer setHidden:NO];
    } else {
        [self.tableView.mj_footer setHidden:YES];
    }
    
    if (page == 1) {
        [tableArray removeAllObjects];
        [self.tableView.mj_footer resetNoMoreData];
    }
    // 数据列表
    NSArray *list = dics[@"list"];
    if (list.count == 0 && page != 1) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        [self getNetFailure];
        return;
    }
    for (NSDictionary *dic in list) {
        CouponModel *model = [CouponModel mj_objectWithKeyValues:dic];
        [tableArray addObject:model];
    }
    [self.tableView reloadData];
}
- (void)getNetData {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:PageSize forKey:@"pageSize"];
    // 状态(0未使用1已使用2可领取)
    switch (self.titleView.currentIndex) {
        case 0:
        {
            [dic setObject:@(_usablePage) forKey:@"pageNumber"];
            [dic setObject:@"2" forKey:@"isuse"];
        } break;
        case 1:
        {
            [dic setObject:@(_unusedPage) forKey:@"pageNumber"];
            [dic setObject:@"0" forKey:@"isuse"];
        } break;
        case 2:
        {
            [dic setObject:@(_usedPage) forKey:@"pageNumber"];
            [dic setObject:@"1" forKey:@"isuse"];
        } break;
        default:
            break;
    }
    
    NSString *url;
    switch (self.type) {
        case CouponFromTypeMine:
        {
            url = URL_Get_Coupon;
        } break;
        case CouponFromTypeGoodsDetail:
        {
            url = URL_Get_GoodsCoupon;
            [dic setObject:self.ids forKey:@"gtrcid"];
            [dic setObject:@"1" forKey:@"pageNumber"];
            [dic setObject:self.number forKey:@"pageSize"];
        } break;
        case CouponFromTypeShopcartOrder:
        {
            url = URL_Get_Coupon_Class;
            [dic setObject:self.ids forKey:@"scids"];
        } break;
        case CouponFromTypeGoodsOrder:
        {
            url = URL_GoodsCoupon;
            [dic setObject:self.ids forKey:@"gid"];
            [dic setObject:self.number forKey:@"number"];
        } break;
        default:
            break;
    }
    
    __block typeof(self) blockSelf = self;
    [MYAFNetworking POST:url parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [blockSelf endRefresh];
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *dic = responseObject[@"data"];
            [blockSelf getNetSuccess:dic];
        } else {
            [blockSelf getNetFailure];
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [blockSelf endRefresh];
        [blockSelf getNetFailure];
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)getNetCouponCount {
    __block typeof(self) blockSelf = self;
    //[MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Get_CouponCount parameters:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            if (responseObject[@"data"] && [responseObject[@"data"] isKindOfClass:[NSArray class]]) {
                [blockSelf.titleCountArray removeAllObjects];
                [blockSelf.titleCountArray addObjectsFromArray:responseObject[@"data"]];
                [blockSelf updateTitleView];
            }
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:blockSelf.view animated:YES];
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (self.titleView.currentIndex) {
        case 0:
            return self.usableArray.count;
        case 1:
            return self.unusedArray.count;
        case 2:
            return self.usedArray.count;
        default:
            return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CouponTableViewCell *cell = [CouponTableViewCell couponTableCellWith:tableView type:self.titleView.currentIndex];
    
    CouponModel *model;
    switch (self.titleView.currentIndex) {
        case 0:
            model = self.usableArray[indexPath.row];
            break;
        case 1:
            model = self.unusedArray[indexPath.row];
            break;
        case 2:
            model = self.usedArray[indexPath.row];
            break;
        default:
            break;
    }
    [cell updateCellWith:model type:self.titleView.currentIndex];
    
    __block typeof(self) blockSelf = self;
    cell.block = ^{
        [blockSelf exchangeAction:model];
    };
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.titleView.currentIndex == 1 && self.type != CouponFromTypeMine) {
        CouponModel *model = self.unusedArray[indexPath.row];
        if (self.block) {
            self.block(model);
        }
        [self disMissSelf];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    [view setBackgroundColor:[UIColor clearColor]];
    return view;
}
#pragma mark - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *alertStr = @"暂无优惠券";
    return [[NSAttributedString alloc] initWithString:alertStr
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [self getNetData];
}
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -44/2;
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
